from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.serializers import SKUSerializer
from users.serializers import AddressTitleSerializer, UserBrowseHistorySerializer
from . import serializers
from . import models
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.

# 　创建用户 /CreateUserView/
class CreateUserView(CreateAPIView):
    serializer_class = serializers.CreateUserSerializer


# 判断用户是否存在
# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    def get(self, request, username):
        count = models.User.objects.filter(username=username).count()
        data = {
            "username": username,
            "count": count,
        }
        return Response(data)


# 判断手机号码是否存在
# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    def get(self, request, mobile):
        count = models.User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count,
        }
        return Response(data)


# 用户详情
class UserDetailVeiw(RetrieveAPIView):
    serializer_class = serializers.UserDetailSerializer
    # 　身份认证
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 　发送邮件验证链接
class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    def get_object(self):
        return self.request.user


# 验证邮箱
class VerifyEmailView(APIView):
    def get(self, request):
        token = request.query_params.get("token")
        # 验证是否收到token
        if not token:
            return Response({"message": "链接信息无效"}, status=status.HTTP_400_BAD_REQUEST)

        user = models.User.check_verify_email_token(token)
        if not user:
            return Response({"message": "无效信息"}, status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()
        return Response({'message': 'OK'})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    serializer_class = serializers.UserAddressSerializer
    pagination_class = [IsAuthenticated]


    def get_queryset(self):
        ret = self.request.user.addresses.filter(is_deleted=False)
        # ret1 = models.Address.objects.filter(user=self.request.user.id)
        return ret

    # 新建地址
    def create(self, request, *args, **kwargs):
        count = self.request.user.addresses.all().count()
        if count > 8:
            return Response({'message': '用户地址超过上限'}, status=status.HTTP_400_BAD_REQUEST)
        return super(AddressViewSet, self).create(request, *args, **kwargs)

    # 显示所有列表详细信息
    def list(self, request):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 4,
            'addresses': serializer.data,
        })

    # 删除，逻辑删除
    def destroy(self,request, *args, **kwargs):
        queryset = self.get_object()
        queryset.is_deleted = True
        return Response(status=status.HTTP_204_NO_CONTENT)


    # 设置默认地址
    @action(methods=["put"], detail=True)
    def status(self, request, pk=None):
        queryset = self.get_object()
        request.user.default_address = queryset
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=["put"], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# # /browse_histories/
# class UserBrowseHistoryView(CreateAPIView):
#     serializer_class = UserBrowseHistorySerializer
#
#     permission_classes = [IsAuthenticated]
#
#     def get(self, request):
#         """
#         获取用户的浏览记录
#         :param request:
#         :return:
#         """
#         # 获取用户Ｉｄ
#         user_id = request.user.id
#         # 链接redis
#         conn = get_redis_connection("history")
#
#         sku_ids = conn.lrange("history_%s" % user_id, 0, -1)
#
#         model_list = []
#         for sku_id in sku_ids:
#             sku_model = SKU.objects.get(id=sku_id)
#             model_list.append(sku_model)
#
#         serializer = SKUSerializer(model_list, many=True)
#         return Response(serializer.data)

class UserBrowseHistoryView(CreateAPIView):
    """保存用户浏览记录"""
    # 指定序列器进行数据的校验
    serializer_class = UserBrowseHistorySerializer

    # 指定只有登录用户才能访问此接口
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取用户的浏览记录"""
        # 获取user_id
        user_id = request.user.id
        # 创建redis连接
        redis_conn = get_redis_connection('history')

        # 取redis中的当前登录用户的所有浏览记录数据
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)

        sku_list = []  # 保存sku模型对象
        # 遍历sku_ids通过sku_id取出每一个sku商品模型对象
        for sku_id in sku_ids:
            sku_model = SKU.objects.get(id=sku_id)
            sku_list.append(sku_model)

        serializer = SKUSerializer(sku_list, many=True)
        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response = super().post(request,*args,**kwargs)
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            # 合并购物车的方法(注意参数的位置)
            merge_cart_cookie_to_redis(request, response, user)

        return response